package com.daxt.common.util;

import cn.hutool.json.JSONObject;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultUtil;
import com.daxt.model.dic.SystemConfigType;
import com.daxt.model.dto.EkpReplaceDisposeDto;
import com.daxt.model.service.base.vo.BaseTask;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.time.LocalDateTime;

/**
 * @description: http请求kep 代办
 * @author: lig
 * @date: 2021-12-15
 */
public class EkpHttpWsUtil{


//    static int socketTimeout = 50000;// 请求超时时间  单位毫秒
//    static int connectTimeout = 50000;// 传输超时时间

    public final static String username = "lqdangan";
    public final static String password = "7b10827649ef0989dcf3ba2b0eff40b6";



    /**
     * @description: 发送待办接口
     *
     * @param flag  1-待办    2-已办
     *
     * @author: lig
     * @date: 2021/11/23
     */
    public static BaseTask todo(EkpReplaceDisposeDto dto,String flag) {


        String todoUrl = "https://ekp.sxlq.com:9000/sys/webservice/sysNotifyTodoWebService?wsdl";
//        String todoUrl = "https://ekp.sxlq.com:9000/sys/webservice/sysNotifyTodoWebService?wsdl";
        String method = "";
        if(flag.equals("1")){
            method = "sendTodo";
            dto.setCreateTime(DateUtil.getCurrentTime(DateUtil.DateFormat.YYYY_MM_DD_HH_mm_ss));
        }
        if(flag.equals("2")){
            method = "setTodoDone";
        }


        String params = buildTodoParam(dto);
        String soapXml = buildTodoSoapXml(params,method);

        System.out.println("---------------------------------");
        if(flag.equals("1"))System.out.println("待办");
        if(flag.equals("2"))System.out.println("已办");
        System.out.println("soapXml:"+soapXml);
        System.out.println("---------------------------------");


        String av = RedisUtil.getSysConfig(SystemConfigType.PROFILES_ACTIVE);
        if(!av.equals("lq")){
            System.err.println("profiles_active:"+av);
            return null;
        }

        String result = HttpWsUtil.postSoap1_1(todoUrl, soapXml, "", null, null);
        System.out.println("#############################");
        System.out.println("todo result:"+result);
        System.out.println("##############################");
        Result resu = parseRestult(result);

        BaseTask baseTask = new BaseTask();
        baseTask.setUrl(todoUrl);
        baseTask.setParam(soapXml);
        baseTask.setResult(result);
        baseTask.setType(method);
        baseTask.setAskNum(1);
        baseTask.setCreateTime(LocalDateTime.now());
        baseTask.setParseResult(resu.getCode());

        return baseTask;
//        return null;


    }
//    /**
//     * @description: 设为已办接口(setTodoDone)
//     *
//     *
//     * @author: lig
//     * @date: 2021/11/23
//     */
//    public static Result<String> setTodoDone(EkpReplaceDisposeDto dto) {
//        String postUrl = "https://ekp.sxlq.com:9000/sys/webservice/sysNotifyTodoWebService?wsdl";
//
////        JSONObject j = new JSONObject();
//////        j.set("LoginName","weideliang");
////        j.set("LoginName",dto.getLoginName());
////        String targets = j.toString();//[{"LoginName":"weideliang"}]
////
////        StringBuffer sb = new StringBuffer();
////        sb.append("<appName>档案系统</appName>");//待办来源
////        sb.append("<createTime>"+DateUtil.getCurrentTime(DateUtil.DateFormat.YYYY_MM_DD)+"</createTime>");
////        sb.append("<modelId>"+dto.getModelId()+"</modelId>");//待办唯一标识
////        sb.append("<modelName>"+dto.getModelName()+"</modelName>");//模块名
////        sb.append("<subject>"+dto.getSubject()+"</subject>");//标题
////        sb.append("<targets>"+dto.getTargets()+"</targets>");//待办所属对象
////        sb.append("<type>"+dto.getType()+"</type>");//待办类型 1-表示审批类待办 2-表示为通知类待办
////
////
////        String soapXml = "<soapenv:Envelope\n" +
////                "xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
////                "xmlns:web=\"http://webservice.notify.sys.kmss.landray.com/\">\n" +
////                "<soapenv:Header>\n" +
////                "<tns:RequestSOAPHeader\n" +
////                "xmlns:tns=\"http://sys.webservice.client\">\n" +
////                "<tns:user>lqdangan</tns:user>\n" +
////                "<tns:password>7b10827649ef0989dcf3ba2b0eff40b6</tns:password>\n" +
////                "</tns:RequestSOAPHeader>\n" +
////                "</soapenv:Header>\n" +
////                "<soapenv:Body>\n" +
////                "<web:setTodoDone>\n" +
////                "<arg0>\n" +
////                sb.toString() +
////                "</arg0>\n" +
////                "</web:setTodoDone>\n" +
////                "</soapenv:Body>\n" +
////                "</soapenv:Envelope>";
//
//
//        String params = buildTodoParam(dto);
//        String soapXml = buildTodoSoapXml(params,"setTodo");
//
//        String result = HttpWsUtil.postSoap1_1(postUrl, soapXml, "", null, null);
//        return parseRestult(result);
//
//
//    }





    /**
     * 解析webservice的返回结果
     *
     * @param str      xml内容
     * @return
     */
    public static Result parseRestult(String str) {
        try {
            Document doc = DocumentHelper.parseText(str);

            //获得指定节点下面的子节点
            Element root = doc.getRootElement();//首先要知道自己要操作的节点。
            Element body = root.element("Body");
            Element getTodoResponse = body.element("getTodoResponse");

            Element ret = getTodoResponse.element("return");
            Element returnState = ret.element("returnState");
            Element message = ret.element("message");

            return ResultUtil.data(returnState.getText(),message.getText(),null);


        } catch (Exception e) {
//            e.printStackTrace();
        }
        return ResultUtil.error("解析失败",str);
    }


    /**
     * @description: 借阅kep操作
     *
     * @author: lig
     * @date: 2022/1/4
     */
    public static BaseTask borrowEkp(String instanceid,String approver,Long applyId){

        String sysHome = RedisUtil.getSysConfig(SystemConfigType.SYS_HOME);
        String approvalUrl = sysHome + "acceptor/work/#/approve?applyId="+applyId+"&approver="+approver;
        System.err.println("审批url===================");
        System.err.println("审批url："+approvalUrl);
        System.err.println("审批url=====================");
        EkpReplaceDisposeDto ekpDto = new EkpReplaceDisposeDto();
        ekpDto.setModelId(instanceid);
        ekpDto.setModelName("借阅");
        ekpDto.setSubject("档案借阅审批");
        ekpDto.setLoginName(approver);
        ekpDto.setType(1);//审批

        ekpDto.setMobileLink(approvalUrl);
        ekpDto.setLink(approvalUrl);
        ekpDto.setPadLink(approvalUrl);

//         发送待办
        return todo(ekpDto,"1");
//        return null;


    }


    /**
     * @description: 借阅kep操作  已办
     *
     * @author: lig
     * @date: 2022/1/4
     */
    public static BaseTask borrowEkpDone(String instanceid,String approver){
        EkpReplaceDisposeDto ekpDto = new EkpReplaceDisposeDto();
        ekpDto.setModelId(instanceid);
        ekpDto.setModelName("借阅");
//        ekpDto.setSubject("档案借阅审批");
        ekpDto.setLoginName(approver);
        ekpDto.setOptType(1);

        // 发送 已办
        return todo(ekpDto,"2");
//        return null;


    }


    private static String buildTodoParam(EkpReplaceDisposeDto dto){
        JSONObject j = new JSONObject();
//        j.set("LoginName","weideliang");
        j.set("LoginName",dto.getLoginName());
        String targets = j.toString();//[{"LoginName":"weideliang"}]

        //<![CDATA[档案系统]]>
        StringBuffer sb = new StringBuffer();
        sb.append("<appName><![CDATA[档案系统]]></appName>");//待办来源

        sb.append("<modelId><![CDATA["+dto.getModelId()+"]]></modelId>");//待办唯一标识
        sb.append("<modelName><![CDATA["+dto.getModelName()+"]]></modelName>");//模块名
        if(StringUtils.isNotEmpty(dto.getSubject()))sb.append("<subject><![CDATA["+dto.getSubject()+"]]></subject>");//标题
        if(StringUtils.isNotEmpty(dto.getLink()))sb.append("<link><![CDATA["+dto.getLink()+"]]></link>");//链接
        if(StringUtils.isNotEmpty(dto.getMobileLink()))sb.append("<mobileLink><![CDATA["+dto.getMobileLink()+"]]></mobileLink>");//移动端链接
        if(StringUtils.isNotEmpty(dto.getPadLink()))sb.append("<padLink><![CDATA["+dto.getPadLink()+"]]></padLink>");//pad端链接
        if(StringUtils.isNotEmpty(dto.getCreateTime()))sb.append("<createTime><![CDATA["+dto.getCreateTime()+"]]></createTime>");//创建时间

        if(null != dto.getOptType())sb.append("<optType><![CDATA["+dto.getOptType()+"]]></optType>");//已办类型


        sb.append("<targets><![CDATA["+targets+"]]></targets>");//待办所属对象
//        sb.append("<targets>"+dto.getTargets()+"</targets>");//待办所属对象
        sb.append("<type><![CDATA["+dto.getType()+"]]></type>");//待办类型 1-表示审批类待办 2-表示为通知类待办
        return sb.toString();

    }

    private static String buildTodoSoapXml(String params,String method){
        String soapXml = "<soapenv:Envelope\n" +
                "xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
                "xmlns:web=\"http://webservice.notify.sys.kmss.landray.com/\">\n" +
                "<soapenv:Header>\n" +
                "<tns:RequestSOAPHeader\n" +
                "xmlns:tns=\"http://sys.webservice.client\">\n" +
                "<tns:user>"+username+"</tns:user>\n" +
                "<tns:password>"+password+"</tns:password>\n" +
                "</tns:RequestSOAPHeader>\n" +
                "</soapenv:Header>\n" +
                "<soapenv:Body>\n" +
                "<web:"+method+">\n" +
                "<arg0>\n" +
                params +
                "</arg0>\n" +
                "</web:"+method+">\n" +
                "</soapenv:Body>\n" +
                "</soapenv:Envelope>";

        return soapXml;

    }



    //测试
    public static void main(String args[]) {
//        getTodo();

//        setTodo();


    }


}
